// Filename:    ResponseListener.cpp
// Author:      John Van Drasek
// Date:		4/2/2011
// Description:


// RUP
#include "RUP.h"
// Threading
#include "pthread.h"
// Application
#include "AJ_Globals.h"
#include "AJ_ResponseListener.h"

pthread_t tResponseListener;
int responseListenerSock;

void DisplayPrompt()
{
	printf("AutoJob:> ");
}

int ResponseListener_Init()
{
	int result = AJ_FAIL;

	int threadID;
	int ret;

	threadID = 2;

	ret = pthread_create(&tResponseListener, NULL, ResponseListener, (void*)threadID);
	ret = pthread_detach(tResponseListener);

	return result;
}

int ResponseListener_Destroy()
{
	int result = AJ_FAIL;

	if(!(pthread_cancel(tResponseListener)))
	{
		printf("Response Listener was stopped successfully!\n");
		rup_close(responseListenerSock);//??? we need to close sock here cause we kill the for loop in chatServer() and it doesn't get done???
	}
	else
	{
		printf("Something went wrong while trying to stop Response Listener!  :(\n");
	}

	return result;
}

void* ResponseListener(void* tID)
{
//	int sock;
	int fromlen;
	struct sockaddr_in from;
	struct pkt inPkt;

	// Assign fromlen to the size of the sockaddr_in struct
	fromlen = sizeof(struct sockaddr_in);

	// Create INTERNET, udp datagram socket
	responseListenerSock = rup_open();

	// Bind protocol to socket
	if(rup_bind(responseListenerSock, CLIENTCHATPORT)) 
	{
		exit(1); 
	}

	// Loop forever reading and writing on port
	for(;;)
	{
		int rc;

		memset(inPkt._msgbuf,0,BUFSIZE);

		DisplayPrompt();
		if ((rc=rup_read(responseListenerSock, &inPkt, sizeof(struct pkt), &from)) < 0 )
		{
			printf("chat server error: errno %d\n",errno);
			perror("reading datagram");
			exit(1);
		}

		// Send chat to everyone who is logged in
		//sendChatToList(chatSock, &from, inPkt._client_name, inPkt._msgbuf);
		printf("\n\nIncoming Response: %s\n", inPkt._msgbuf);
	}
	//rup_close(sock);  // FIXME: commented out because compiler warns it is unreachable code
}